﻿// Coursework Scripts

// variable that represents the captcha, whether it is
// successful or not
var captchaSuccess = false;

// Method for the autocomplete to execute
// using the web api method
$(function () {
    $('#txtSearch').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/api/search',
                type: 'GET',
                cache: false,
                data: request,
                dataType: 'json',
                success: function (json) {
                    // call autocomplete callback method with results  
                    response($.map(json, function (name, val) {
                        return {
                            label: name,
                            value: val
                        }
                    }));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert('error - ' + textStatus);
                    console.log('error', textStatus, errorThrown);
                }
            });
        },
        focus: function (event, ui) {
            this.value = ui.item.label;
            event.preventDefault(); // Prevent the default focus behavior.
        },
        minLength: 4,
        select: function (event, ui) {
            alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
            $('#txtSearch').val(ui.item.label);
            window.location.href = "/Employee/Details?id=" + ui.item.value;
            return false;
        }
    })
});

// method that validates the captcha
function Captcha() {

    $('#status').attr('class', 'inProgress');
    $('#status').text('Checking...');

    // get client-side Captcha object instance
    var captchaObj = $("#CaptchaCode").get(0).Captcha;

    // gather data required for Captcha validation
    var params = {}
    params.CaptchaId = captchaObj.Id;
    params.InstanceId = captchaObj.InstanceId;
    params.UserInput = $("#CaptchaCode").val();

    // make asynchronous Captcha validation request
    $.getJSON('CheckCaptcha', params, function (result) {
        if (true === result) {
            $('#status').attr('class', 'correct');
            $('#status').text('Check passed');

        } else {
            $('#status').attr('class', 'incorrect');
            $('#status').text('Check failed');

            // always change Captcha code if validation fails
            captchaObj.ReloadImage();
        }
        captchaSuccess = result;
    });

    return captchaSuccess;
}



    //$('#sumbitButton').attr("onclick", null)
    //.removeAttr("onclick")
    //.click(function () {
    //    // alert("fooo");
    //    if (($("#txtbxPassword").val().length > 5) && ($("#txtbxPassword").val().length > 0)) {
    //        Captcha();
    //        //alert("submit disabled");
    //        // only if the captcha function is correct then proceed

    //        //if (captchaSuccess === true) {
    //        //    WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
    //        //}
    //    }
    //});


    ///////////////////////////////////////////////////////



    /////////////////////////////// The Kendo UI Grid
   

$(document).ready(function () {

    $("#sumbitButton").click(function (evt) {
        if (($("#txtbxPassword").val().length > 5) && ($("#txtbxPassword").val().length > 0)) {
            var captchaValue = Captcha();
            if (captchaValue === true) {
                // alert("submit disabled");
                // only if the captcha function is correct then proceed
                WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
            }            
            else {
                evt.preventDefault();
            }
        }
    });

    $('select#cmbbxchoices').selectmenu({
        icons: [
        { find: '.script', icon: 'ui-icon-script' },
        { find: '.image', icon: 'ui-icon-image' }
        ]
    });

    //$('#filesC').on('change', function () {
    //    var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
    //    var comp = this.options[this.selectedIndex];
    //    alert(comp.value);
    //    console.log(label);
    //});

    $("#Button1").click(function () {
     
        var crudServiceBaseUrl = "api/search/";
        var dropdwnChoices = $("#choices").val();
        var textbxEmpName = $("#btnSearchMulti").val();
    

        var grid = $("#grid").kendoGrid({
            // specify the columns on the grid
            columns: [

                { field: "emp_no", title: "Employee No" },

                { field: "first_name", title: "First Name", width: "150px" },

                { field: "last_name", title: "Last Name", width: "150px" },

                { field: "gender", title: "Gender", width: "100px" },

                { command: ["edit", "destroy"], title: "&nbsp;", width: "210px" }

            ],

            detailTemplate: kendo.template($("#template").html()),


            // the datasource for the grid
            dataSource: new kendo.data.DataSource({
                // the transport tells the datasource what endpoints
                // to use for CRUD actions
                transport: {
                    read: {
                        // crudServiceBaseUrl + "GetEmployees?empName=" + textbxEmpName,
                        url: crudServiceBaseUrl,
                        type: "POST",
                        contentType: "application/json"
                    },
                    update: {
                        // get the id off of the model object that
                        // kendo ui automatically passes to the url function
                        url: function (employee) {
                            return crudServiceBaseUrl + employee.emp_no
                        },

                        type: "POST",
                        dataType: "json"
                    },
                    destroy: {
                        // get the id off of the model object that
                        // kendo ui automatically passes to the url function
                        url: function (employee) {
                            return "api/employees/" + employee.emp_no
                        },
                        type: "DELETE"
                    },
                    parameterMap: function (options, operation) {
                        if (operation === "read") {

                            var extendedK = new ExtendedKendo();
                            extendedK.ParseOriginalKendo(options);
                            // convert the parameters to a json object
                            return kendo.stringify(extendedK);
                        }
                        // if the current operation is an update
                        if (operation === "update") {
                            // create a new JavaScript date object based on the current
                            // BirthDate parameter value
                           // var d = new Date(options.BirthDate);
                            // overwrite the BirthDate value with a formatted value that WebAPI
                            // will be able to convert
                            //options.BirthDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                        }
                        // ALWAYS return options
                        return options;
                    }
                },
                // the schema defines the schema of the JSON coming
                // back from the server so the datasource can parse it
                schema: {
                    // the array of repeating data elements (employees)
                    data: "Data",
                    // the total count of records in the whole dataset. used
                    // for paging.
                    total: "Count",

                    model: {

                        id: "emp_no",

                        fields: {

                            emp_no: { type: "number", editable: false, nullable: false },

                            first_name: { editable: false, validation: { required: true } },

                            last_name: { validation: { required: true } },

                            gender: { editable: false, validation: { required: true } }

                        }
                    },

                    // map the errors if there are any. this automatically raises the "error" 
                    // event
                    errors: "Errors"
                },
                error: function (e) {
                    console.log(e.statusText);
                },
                // the number of records to show per page
                pageSize: 20,
                // do paging on the server
                serverPaging: true,
                // do sorting on the server
                serverSorting: true,

            }),

            // paging is enabled in the grid
            pageable: true,
            // editing happens inline, one row at a time.
            editable: "popup",

            filterable: true,

            selectable: true,
            // sort by multiple columns
            sortable: {
                mode: "multiple"
            },

            detailTemplate: kendo.template($("#template").html()),
            toolbar: kendo.template($("#toolBarTemplate").html()),
            detailInit: detailInit,
            change: function (e) {
                // get the current item selected in the grid
                var employee = this.dataSource.getByUid(this.select().data("uid"));
                // write out the employee id
                console.log(employee.id);
            }
        });//.data("kendoGrid");

       // the kendo dropdown that uses filters
        var dropDown = grid.find("#requestType").kendoDropDownList({
            dataTextField: "deptName",
            dataValueField: "deptNo",
            autoBind: false,
            optionLabel: "All",
            dataSource: {
                type: "json",
                transport:
                    {
                        read: {
                            url: "Department/GetDepartments/",
                            contentType: "application/json"
                        }
                    },
                schema: {
                    // the array of repeating data elements (employees)
                    data: "Data",
                    // the total count of records in the whole dataset. used
                    // for paging.
                    total: "Count",
                }
            },
            change: function () {
                var value = this.value();
                if (value) {
                    grid.data("kendoGrid").dataSource.filter(
                        { field: "deptName", operator: "eq", value: value });
                } else {
                    grid.data("kendoGrid").dataSource.filter({});
                }
            }
        });
    });

    

// Detail init function for the first kendo grid
    function detailInit(e) {
        var detailRow = e.detailRow;
        var empNo = e.data.emp_no;
        detailRow.find("#tabstrip").kendoTabStrip();
        detailRow.find("#salaryDetails").kendoGrid({
            dataSource: {
                type: "json",
                transport:
                    {
                        read: {
                            url: "Employee/GetSalaryLog/", type: "POST",
                            contentType: "application/json"
                        },
                        parameterMap: function (options, operation, e) {
                            if (operation === "read") {

                                var extendedK = new ExtendedKendo();
                                extendedK.ParseOriginalKendo(options, true, empNo);
                                // convert the parameters to a json object
                                return kendo.stringify(extendedK);
                            }
                            // if the current operation is an update
                            if (operation === "update") {
                                // create a new JavaScript date object based on the current
                                // BirthDate parameter value
                                var d = new Date(options.BirthDate);
                                // overwrite the BirthDate value with a formatted value that WebAPI
                                // will be able to convert
                                options.BirthDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                            }
                            // ALWAYS return options
                            return options;
                        }
                    },
                schema: {
                    // the array of repeating data elements (employees)
                    data: "Data",
                    // the total count of records in the whole dataset. used
                    // for paging.
                    total: "Count",
                    model: {
                        id: "empNo",

                        fields: {

                            empNo: { type: "number", editable: false, nullable: false },

                            salary: { type: "number" },

                            startDate: { type: "date" },

                            endDate: { type: "date" }

                        }

                    },

                    parse: function (response) {
                        for (var i = 0; i < response.Data.length; i++) {
                            response.Data[i].endDate;
                            if (response.Data[i].endDate !== undefined) {
                                if (response.Data[i].endDate === "/Date(253370745000000)/") {
                                    response.Data[i].endDate = null;
                                }
                            }
                           
                        }
                        return response;
                    }
                  
                },

                serverPaging: true,

                serverSorting: true,

                serverFiltering: true,

                pageSize: 6,

               
            },

            pageable: true,

            //height: 200,

            columns: [
                { field: "salary", title: "Salary", format: "{0:c}" },

                { field: "startDate", title: "Start Date", template: '#= kendo.toString(startDate,"MM/dd/yyyy") #' },

                { field: "endDate", title: "End Date", template: "#= (endDate == null) ? 'Current' : kendo.toString(endDate, 'MM/dd/yyyy') #" }
            ]
        });

        detailRow.find("#titleHistory").kendoGrid({
            dataSource: {
                type: "json",
                transport:
                    {
                        read: {
                            url: "Employee/GetTitles/", type: "POST",
                            contentType: "application/json"
                        },
                        parameterMap: function (options, operation, e) {
                            if (operation === "read") {

                                var extendedK = new ExtendedKendo();
                                extendedK.ParseOriginalKendo(options, true, empNo);
                                // convert the parameters to a json object
                                return kendo.stringify(extendedK);
                            }
                            // if the current operation is an update
                            if (operation === "update") {
                                // create a new JavaScript date object based on the current
                                // BirthDate parameter value
                                var d = new Date(options.BirthDate);
                                // overwrite the BirthDate value with a formatted value that WebAPI
                                // will be able to convert
                                options.BirthDate = kendo.toString(new Date(d), "MM/dd/yyyy");
                            }
                            // ALWAYS return options
                            return options;
                        }
                    },
                schema: {
                    // the array of repeating data elements (employees)
                    data: "Data",
                    // the total count of records in the whole dataset. used
                    // for paging.
                    total: "Count",
                    model: {
                        id: "empNo",

                        fields: {

                            empNo: { type: "number", editable: false, nullable: false },

                           // department: { editable: false },

                            fromDate: { type: "date" },

                            toDate: { type: "date" },

                            title: { editable: false }

                        }

                    },

                    parse: function (response) {
                        for (var i = 0; i < response.Data.length; i++) {
                            response.Data[i].toDate;
                            if (response.Data[i].toDate !== undefined) {
                                if (response.Data[i].toDate === "/Date(253370745000000)/") {
                                    response.Data[i].toDate = null;
                                }
                            }

                        }
                        return response;
                    }

                },

                serverPaging: true,

                serverSorting: true,

                serverFiltering: true,

                pageSize: 6,


            },

            pageable: true,

           // height: 200,

            columns: [
                { field: "title", title: "Title" },

                { field: "fromDate", title: "Start Date", template: '#= kendo.toString(fromDate,"MM/dd/yyyy") #' },

                { field: "toDate", title: "End Date", template: "#= (toDate == null) ? 'Current' : kendo.toString(toDate, 'MM/dd/yyyy') #" }
            ]
        });
    }





// JQuery initializer for the datefield
    $(".datefield").click(function () {
        $(".datefield").datepicker();
        $(".datefield").datepicker("show");
    });


    // end of document.ready
});





$(document).ready(function () {
    $("#lblempId").prop("disabled", true);
    $("#frmNewEmployee").hide();

    $("#btnEmployee").click(function (evt) {
        evt.preventDefault();
        var jsonPacket = form2js(document.getElementById('frmNewEmployee'));
        alert(jsonPacket);
        $.ajax({
            type: "POST",
            url: "Employee/Create",
            data: JSON.stringify(jsonPacket.employee),
            contentType: 'application/json; charset=utf-8',           
            async: false,
            success: function (result) {
                console.log("success");
                $("#grid").data("kendoGrid").dataSource.read();
            },
            error: function (e) {
                alert(e);
            }
        });
      

    });
    
    $("#clickMe").click(function () {
        var defaultValue;
        if ($("#frmNewEmployee").is(':visible') === false) {
            var parameters = { UserId: '' }
            $("#frmNewEmployee").show();
            $.ajax({
                type: "POST",
                url: "Employee/GetLatestId",
                data: parameters,
                charset: "utf-8",
                dataType: "json",
                async: false,
                success: function (result) {
                    $("#txtbxempId").val(result);
                    $("#txtbxempId").prop("disabled", true);
                },
                error: function (e) {
                    alert(e);
                }
            });
        }
        else {
            $("#frmNewEmployee").hide();
        }

    });
        
});




function ExtendedKendo() {
    this.take = '';
    this.skip = '';
    this.pageSize = '';
    this.group = undefined;
    this.searchTerm = '';
    this.searchType = '';
    this.emp_no = '';
    this.filter = undefined;
}

ExtendedKendo.prototype.ParseOriginalKendo = function (kendoObject, empFlag, emp_no) {
    this.take = kendoObject.take;
    this.skip = kendoObject.skip;
    this.pageSize = kendoObject.pageSize;
    this.group = kendoObject.group;
    this.searchTerm = $("#txtbxSearchMulti").val();
    this.searchType = $("#cmbbxchoices").val();
    if (empFlag === true) {
        this.emp_no = emp_no;
    }
    this.filter = kendoObject.filter;
   
};
